//
//  SubscribeNewsDetailViewController.m
//  suRead
//
//  Created by lidi on 2018/12/5.
//  Copyright © 2018 bao. All rights reserved.
//

#import "SubscribeNewsDetailViewController.h"
#import "Masonry.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "ShareService.h"
#import "ServiceNews.h"
#import "M_NewsDetail.h"
#import "NewsCommentViewController.h"
#import "FMDBHelpers.h"
#import "NewsBridge.h"
#import "NewsWebViewController.h"
#import "NewsSpeechManager.h"

#import <MobLink/MobLink.h>
#import <MobLink/MLSDKScene.h>
#import "ShareView.h"
#import "FontSelectorView.h"
#import "ShareService.h"
#import "NewsDetailViewController.h"
#import "SubscribeNewsListViewController.h"
#import "M_Subscribe.h"
#import "AnalyticsManager.h"
#import "LoginViewController.h"
#import "AccountManager.h"
#import "ServiceUserNew.h"

@interface SubscribeNewsDetailViewController ()<UIWebViewDelegate>
@property (nonatomic,strong) UIWebView *newsWebView;

@property (nonatomic,strong) UILabel *labelCommentCount;

@property (nonatomic,assign) CGFloat fontSizeScaleRate;

@property (nonatomic,strong) UIButton *buttonPraise;

@property (nonatomic,strong) NewsBridge *bridge;

//@property (nonatomic,strong) WebViewJavascriptBridge* webviewBridge;

@property (nonatomic, strong) NSMutableArray<UIImageView *> *imageViews;
@property (nonatomic, strong) NSArray *imageUrls;
@property (nonatomic,strong) M_NewsDetail *newsDetail;
@property (nonatomic, copy) NSString *mobid;

//统计
@property(nonatomic,strong)NSString *targetId;
@property(nonatomic,strong)NSString *targetUrl;

@end

@implementation SubscribeNewsDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.targetId && [self.targetId length] > 0) {
        [AnalyticsManager event:AnalyticsEventType_comeIn targetId:self.targetId url:self.targetUrl];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.targetId && [self.targetId length] > 0) {
        [AnalyticsManager event:AnalyticsEventType_leave targetId:self.targetId url:self.targetUrl];
    }
}

- (void)getMobId
{
    // 构造自定义参数（可选）
    NSMutableDictionary *customParams = [NSMutableDictionary dictionary];
    customParams[@"type"] = @"newsDetail";
    customParams[@"urlString"] = self.urlString;
    // 根据路径、来源以及自定义参数构造scene
    MLSDKScene *scene = [[MLSDKScene alloc] initWithMLSDKPath:@"" source:@"iOS" params:customParams];
    // 请求MobId
    __weak typeof(self) weakSelf = self;
    [MobLink getMobId:scene result:^(NSString *mobid, NSError *error) {
        weakSelf.mobid = mobid;
    }];
}

- (void)viewDidLoad {
    
    //    self.urlString = @"http://www3.ctdsb.net/index.php?m=app&c=index&a=get_news&type=doc&aid=14933";
    
    [super viewDidLoad];
    
    [self getMobId];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_WORKING || [SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_PAUSED) {
            [[NewsSpeechManager shared] showStatusView];
        }
    });
    
    self.fontSizeScaleRate = 1.0f;
    self.navigationController.navigationBarHidden = YES;
    [self setNeedsStatusBarAppearanceUpdate];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weak_self = self;
    
    self.newsWebView = [UIWebView new];
    self.newsWebView.backgroundColor=[UIColor clearColor];
    for (UIView *subView in [self.newsWebView subviews])
    {
        if ([subView isKindOfClass:[UIScrollView class]])
        {
            //((UIScrollView *)subView).bounces = NO; //去掉UIWebView的底图
            [(UIScrollView *)subView setShowsVerticalScrollIndicator:NO]; //右侧的滚动条
            [(UIScrollView *)subView setShowsHorizontalScrollIndicator:NO]; //右侧的滚动条
            
            for (UIView *scrollview in subView.subviews)
            {
                if ([scrollview isKindOfClass:[UIImageView class]])
                {
                    scrollview.hidden = YES;  //上下滚动出边界时的黑色的图片
                }
            }
        }
    }
    self.newsWebView.backgroundColor = [UIColor whiteColor];
    //    UIPinchGestureRecognizer *gesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(switchFontSize:)];
    //    [self.newsWebView addGestureRecognizer:gesture];
    
    self.bridge = [NewsBridge bridgeForWebView:self.newsWebView webViewDelegate:self];
    [self.bridge setToNewsDetailCallBack:^(NSString *url) {
        NewsDetailViewController *controller = [NewsDetailViewController new];
        controller.urlString = url;
        //        controller.f_thumbnail = weak_self.f_thumbnail;
        if ( [[[UIDevice currentDevice]systemVersion] floatValue] >= 8.0) {
            [weak_self showViewController:controller sender:weak_self];
        }else{
            [weak_self.navigationController pushViewController:controller animated:YES];
        }
    }];
    
    [self.bridge setADCallBack:^(NSString *url) {
        NewsWebViewController *controller = [NewsWebViewController new];
        controller.hidesBottomBarWhenPushed = YES;
        controller.urlString = url;
        //        controller.imgUrlString = news_.f_thumbnail;
        //        controller.titleString = news_.f_title;
        controller.hasShare = NO;
        [weak_self.navigationController pushViewController:controller animated:YES];
        
    }];
    
    UIView *bottomBarView = [UIView new];
    bottomBarView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.newsWebView];
    [self.view addSubview:bottomBarView];
    [bottomBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weak_self.view);
        if (iPhoneX) {
            make.top.equalTo(bottomBarView.superview).offset(44.0f);
        } else {
            make.top.equalTo(bottomBarView.superview).offset(20.0f);
        }
        make.height.equalTo(@44.0f);
    }];
    [self.newsWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomBarView.mas_bottom);
        make.left.right.equalTo(weak_self.view);
        if (iPhoneX) {
            make.bottom.equalTo(weak_self.view).offset(-34.0f);
        } else {
            make.bottom.equalTo(weak_self.view);
        }
    }];
    
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //返回
        [weak_self.navigationController popViewControllerAnimated:YES];
        [weak_self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    UIButton *buttonViewComment = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonViewComment setImage:[UIImage imageNamed:@"btn_comments"] forState:UIControlStateNormal];
    [buttonViewComment addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //查看评论列表
        NewsCommentViewController *newsCommentViewController = [[NewsCommentViewController alloc] init];
        newsCommentViewController.commentsUrl = weak_self.newsDetail.f_commentsUrl;
        newsCommentViewController.commentId = weak_self.newsDetail.f_commentid;
        newsCommentViewController.targetId = weak_self.targetId;
        newsCommentViewController.targetUrl = weak_self.targetUrl;
        [weak_self.navigationController pushViewController:newsCommentViewController animated:YES];
    }];
    
    self.buttonPraise = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.buttonPraise setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
    [self.buttonPraise addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
         
         if (![AccountManager sharedAccountManager].f_isLogined) {
             // 需要登录
             UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
             LoginViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
             controller.hidesBottomBarWhenPushed = YES;
             [weak_self.navigationController showViewController:controller sender:nil];
             return;
         }
         
         if (![[FMDBHelpers sharedInstance] queryData:weak_self.newsDetail.f_docid type:0]) {
             
             if (weak_self.targetId && [weak_self.targetId length] > 0) {
                 [AnalyticsManager event:AnalyticsEventType_praise targetId:weak_self.targetId url:weak_self.targetUrl];
             }
             
             //赞
             [weak_self showHUDProgress:@""];
             [ServiceUserNew doLike:weak_self.newsDetail.f_docid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                 [weak_self removeHUDProgress];
                 [[FMDBHelpers sharedInstance] insertData:weak_self.newsDetail.f_docid andType:0];
                 [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praised"] forState:UIControlStateNormal];
             } failure:^(NSString * _Nonnull message) {
                 [weak_self removeHUDProgress];
                 [weak_self showHUDText:message];
             }];
         } else {
             //取消点赞
             [weak_self showHUDProgress:@""];
             [ServiceUserNew doUnLike:weak_self.newsDetail.f_docid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                 [weak_self removeHUDProgress];
                 [[FMDBHelpers sharedInstance] deleteData:weak_self.newsDetail.f_docid type:0];
                 [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
             } failure:^(NSString * _Nonnull message) {
                 [weak_self removeHUDProgress];
                 [weak_self showHUDText:message];
             }];
         }
     }];
    
    UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [playButton setImage:[UIImage imageNamed:@"news_detail_read"] forState:UIControlStateNormal];
    [playButton addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [[NewsSpeechManager shared] speechNewsDetail:weak_self.newsDetail];
    }];
    
    UIButton *buttonShare = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonShare setImage:[UIImage imageNamed:@"button_news_detail_more"] forState:UIControlStateNormal];
    [buttonShare addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        
        BOOL hadInstalledWeixin = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]];
        BOOL hadInstalledQQ = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]];
        
        NSMutableArray *titlearr     = [NSMutableArray arrayWithCapacity:5];
        NSMutableArray *imageArr     = [NSMutableArray arrayWithCapacity:5];
        NSMutableArray *typeArr     = [NSMutableArray arrayWithCapacity:5];
        
        if (hadInstalledWeixin) {
            [titlearr addObjectsFromArray:@[@"微信", @"微信朋友圈"]];
            [imageArr addObjectsFromArray:@[@"UMS_wechat_icon",@"UMS_wechat_timeline_icon"]];
            [typeArr addObjectsFromArray:@[@(ShareTypeWechatSession), @(ShareTypeWechatTimeLine)]];
        }
        if (hadInstalledQQ) {
            [titlearr addObjectsFromArray:@[@"QQ"]];
            [imageArr addObjectsFromArray:@[@"UMS_qq_icon"]];
            [typeArr addObjectsFromArray:@[@(ShareTypeQQ)]];
        }
        [titlearr addObjectsFromArray:@[@"微博"]];
        [imageArr addObjectsFromArray:@[@"UMS_sina_icon"]];
        [typeArr addObject:@(ShareTypeSina)];
        
        //更多按钮事件
        ShareView *shareView = [[ShareView alloc] initWithShareHeadOprationWith:titlearr andImageArry:imageArr fontHandle:^() {
            FontSelectorView *fontView = [[FontSelectorView alloc] initWithHandle:^(CGFloat font) {
                [weak_self setFontSize:font];
            }];
            [[UIApplication sharedApplication].keyWindow addSubview:fontView];
            [fontView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(fontView.superview);
            }];
        }];
        [shareView setBtnClick:^(NSInteger btnTag) {
            
            NSString *shareUrl_ = weak_self.newsDetail.f_source_url;
            
            if ([shareUrl_ rangeOfString:@"?"].location != NSNotFound)
            {
                shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&uct=%@",[ServiceNews getAuthCode]]];
                if (self.mobid) {
                    shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"&mobid=%@",self.mobid]];
                }
            } else {
                if (self.mobid) {
                    shareUrl_ = [shareUrl_ stringByAppendingString:[NSString stringWithFormat:@"?mobid=%@",self.mobid]];
                }
            }
            
            UIImage *shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:weak_self.f_thumbnail]]];
            if (!shareImage) {
                shareImage = [UIImage imageNamed:@"shareIcon.png"];
            }
            
            NSString *shareTitle = weak_self.newsDetail.f_title;
            
            
            [weak_self shareToPlatform:[typeArr[btnTag] integerValue] title:shareTitle des:shareTitle icon:shareImage url:shareUrl_];
        }];
        [[UIApplication sharedApplication].keyWindow addSubview:shareView];
    }];
    
    UILabel *linelab = [UILabel new];
    linelab.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    [bottomBarView addSubview:linelab];
    
    [bottomBarView addSubview:buttonBack];
    [bottomBarView addSubview:buttonViewComment];
    [bottomBarView addSubview:playButton];
    [bottomBarView addSubview:self.buttonPraise];
    [bottomBarView addSubview:buttonShare];
    
    [linelab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bottomBarView);
        make.height.equalTo(@0.5f);
    }];
    
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomBarView);
        make.left.equalTo(bottomBarView).with.offset(8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [buttonShare mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bottomBarView);
        make.right.equalTo(bottomBarView).with.offset(-8.0f);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(buttonShare.mas_left).with.offset(-8.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [buttonViewComment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(playButton.mas_left).with.offset(-8.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    [self.buttonPraise mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(buttonViewComment.mas_left).with.offset(-8.0f);
        make.centerY.equalTo(bottomBarView);
        make.width.equalTo(@28.0f);
        make.height.equalTo(@28.0f);
    }];
    
    self.labelCommentCount = [UILabel new];
    self.labelCommentCount.textAlignment = NSTextAlignmentCenter;
    self.labelCommentCount.textColor = [UIColor whiteColor];
    self.labelCommentCount.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:9.0f];
    [bottomBarView addSubview:self.labelCommentCount];
    [self refreshCommentLabelWith:@"0"];
    
    if (!self.newsDetail) {
        [self refreshData];
    }
}

- (void)shareToPlatform:(ShareType)type title:(NSString *)title des:(NSString *)des icon:(UIImage *)icon url:(NSString *)url {
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:des thumImage:icon];
    //设置网页地址
    shareObject.webpageUrl = url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    UMSocialPlatformType platformType;
    switch (type) {
        case ShareTypeWechatSession:
            platformType = UMSocialPlatformType_WechatSession;
            break;
        case ShareTypeWechatTimeLine:
            platformType = UMSocialPlatformType_WechatTimeLine;
            break;
        case ShareTypeQQ:
            platformType = UMSocialPlatformType_QQ;
            break;
        case ShareTypeSina:
            platformType = UMSocialPlatformType_Sina;
            break;
        default:
            break;
    }
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        
        if (self.targetId && [self.targetId length] > 0) {
            [AnalyticsManager event:AnalyticsEventType_forward targetId:self.targetId url:self.targetUrl];
        }
        
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}

- (void)refreshData
{
    __weak typeof(self) weak_self = self;
    [self showHUDProgress:@""];
    [ServiceNews doFetchNewsDetail:self.urlString success:^(id responseObject, NSString *message) {
        [weak_self removeHUDProgress];
        [weak_self computeHTMLWithNews:responseObject];
        weak_self.newsDetail = responseObject;
        weak_self.newsDetail.urlString = weak_self.urlString;
        weak_self.newsDetail.f_thumbnail = weak_self.f_thumbnail;
        [weak_self refreshCommentLabelWith:weak_self.newsDetail.f_comments];
        
        // 统计
        weak_self.targetId = weak_self.newsDetail.f_docid;
        weak_self.targetUrl = weak_self.urlString;
        [AnalyticsManager event:AnalyticsEventType_comeIn targetId:weak_self.targetId url:weak_self.targetUrl];
        
        if ([AccountManager sharedAccountManager].f_isLogined && [[FMDBHelpers sharedInstance] queryData:weak_self.newsDetail.f_docid type:0]) {
            [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praised"] forState:UIControlStateNormal];
        } else {
            [weak_self.buttonPraise setImage:[UIImage imageNamed:@"btn_praise"] forState:UIControlStateNormal];
        }
    } failure:^(NSString *message) {
        [weak_self removeHUDProgress];
        [weak_self showHUDText:message];
    }];
}

- (void)refreshCommentLabelWith:(NSString *)commentCount
{
    self.labelCommentCount.text = commentCount;
    
    CGFloat width_ = [commentCount sizeWithAttributes:@{NSFontAttributeName:self.labelCommentCount.font}].width + 10.0f;
    width_ = width_ < 25.0f ? 25.0f : width_;
    CGFloat x_ = [UIScreen mainScreen].bounds.size.width - 58.0f - width_ / 2;
    
    [self.labelCommentCount mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.labelCommentCount.superview).offset(8.0f);
        make.left.equalTo(self.labelCommentCount.superview).offset(x_);
        make.width.equalTo(@(width_));
    }];
}

- (void)computeHTMLWithNews:(M_NewsDetail *)news_
{
    NSString *style = @"";
    if (news_.f_style != nil && ![news_.f_style isEqualToString:@""]) {
        style = news_.f_style;
        style = [style stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        style = [style stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    }
    
    NSString *jsString = [NSString stringWithFormat:@"<html> \n"
                          "<head> \n"
                          " <meta charset='utf-8'>\n"
                          "<meta name='format-detection' content='telephone=no'/>\n"
                          "<meta name='viewport' content='user-scalable=yes, initial-scale=1.0, user-scalable=no, width=device-width'/>\n"
                          "<style type=\"text/css\"> \n"
                          "@font-face {font-family: \"kct\";src: url(\"file:///android_asset/kcttext.ttf\")} "
                          "p, div {font-family: kct;text-align:justify;word-break:break-all; line-height:1.5em; color:rgb(40,40,40)} p{text-indent: 2em;}\n"
                          "p img{align:left;width:100%%;margin:0 auto;}"
                          " a > img {display: block;}"
                          " p > img {display: block;}"
                          " img { width:100%%;}"
                          ".newtitle{color: #000; font-size: 1.75rem; margin: 1.2rem 0rem 0rem 0rem; font-weight: lighter;line-height: 1.95rem; font-family:FZTYSK--GBK1-0;}"
                          ".subtitle{color: #747474; font-size: .7rem; margin-top: 1.35rem; font-family:FZBIAOYSJW--GB1-0;}"
                          "#news_content * { font-family:FZBIAOYSJW--GB1-0; }"
                          ".username{float:right;color: #747474;font-size: 1.0rem;font-weight:normal; font-family:FZBIAOYSJW--GB1-0;}"
                          ".rel_news {margin-top: 3.5rem; font-family:FZBIAOYSJW--GB1-0;}"
                          ".rel_news h1 {margin-bottom: 10px;font-size: 1.2rem;color: #28292d;line-height: 19px;border-left: 4px solid #2B61C0;padding-left: 11px;} \n"
                          ".rel_title {color: #747474;font-size: 1.0rem; font-family:FZBIAOYSJW--GB1-0;}\n"
                          ".rel_subtitle{color: #747474;font-size: .7rem;line-height:1.2em; font-family:FZBIAOYSJW--GB1-0;}\n"
                          ".rel_news .itemlist a {display: block;padding: 0 5px;overflow: hidden;text-decoration: none;}\n"
                          ".rel_news .itemlist .item {border-bottom: 1px solid #e3e5e7;position: relative;padding-bottom: 5px;}\n"
                          "</style> \n"
                          "<script src='http://www3.ctdsb.net/statics/js/kctjs.js'></script>\n"
                          "%@ \n"
                          "</head> \n"
                          "<body>"
                          "<h1 class=\"newtitle\">%@</h1>"
                          
                          "<div style='height:40px;margin-top:15px;'>"
                          "<img onclick='window.location.href=\"gotoSubscribeInfo\"' style='float:left;margin:5px 0;width:30px;height:30px;-moz-border-radius: 15px;-webkit-border-radius: 15px;border-radius:15px;' src='%@'/>"  //头像
                          "<div onclick='window.location.href=\"gotoSubscribeInfo\"' style='margin-left:5px;float:left;height:40px;line-height:40px;color: #747474;font-size: .8rem;font-family:FZBIAOYSJW--GB1-0;' >%@</div>" //名字
                          "<div style='height:40px;line-height:40px;float:right;' class=\"subtitle\">%@</div>" //时间
                          "</div>"
                          
                          "<div id=\"news_content\">%@</div>"
                          "<span class='username'>编辑：" "%@</span>",style,news_.f_title,news_.f_service_img,news_.f_source,news_.f_ptime,news_.f_body,news_.f_username];
    
    if (news_.f_adv) {
        jsString = [jsString stringByAppendingString:[NSString stringWithFormat:@"<div style=\"text-align: center;margin-top: 3.5rem;\">"
                                                      "<a href='javascript:;' onclick='_KCT_H5NewsDetail(\"%@\")'>"
                                                      "<img src=\"%@\">"
                                                      "</a></div>",[news_.f_adv objectForKey:@"url"],[news_.f_adv objectForKey:@"img"]]];
    }
    
    if (news_.f_relation && [news_.f_relation count])
    {
        jsString = [jsString stringByAppendingString:@"<div class='rel_news'> \n <h1>相关新闻</h1>\n <div class='itemlist'>\n"];
        
        for (M_NewsDetailRelation *relation in news_.f_relation) {
            NSString *relationtitle = relation.f_title;
            NSString *url = relation.f_url;
            
            jsString = [jsString stringByAppendingFormat:@"<a href='javascript:;' onclick='_KCT_NewsDetail(\"%@\")' > <div class='item'> <h2 class='rel_title'>%@</h2> <div class='rel_subtitle'>%@</div> </div>\n</a>",url,relationtitle,relation.f_inputtime];
        }
        
        jsString = [jsString stringByAppendingString:@"</div>\n</div>"];
    }
    
    jsString = [jsString stringByAppendingString:@"</body> </html>"];
    
    jsString = [jsString stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    jsString = [jsString stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    
    //获取新闻内页图片，提供点击大图展示 Ethan
    NSString *callImage =[NSString stringWithFormat:
                          @"<script type=\"text/javascript\">"
                          "var objs = document.getElementById('news_content').getElementsByTagName('img'); "
                          "var imgArr = [];"
                          "for(var i=0;i<objs.length;i++)  "
                          "{"
                          "imgArr.push(objs[i].src);"
                          "objs[i].id='imgindex_'+i;"
                          "    objs[i].onclick=function()  "
                          "    {  var newimgArr= imgArr;  newimgArr.push(this.id);"
                          "     window.KCT_JS_Interface.openImage(newimgArr);"
                          "    }  "
                          "}"
                          "</script>"];
    
    jsString = [jsString stringByAppendingFormat:@"%@",callImage];
    
    [self.newsWebView loadHTMLString:jsString baseURL:nil];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType API_DEPRECATED("No longer supported.", ios(2.0, 12.0)) {
    
    if ([request.URL.absoluteString hasSuffix:@"gotoSubscribeInfo"]) {
        SubscribeNewsListViewController *controller = [SubscribeNewsListViewController new];
        M_Subscribe *sub = [M_Subscribe new];
        sub.f_wid = self.newsDetail.f_wid;
        sub.f_service_img = self.newsDetail.f_service_img;
        sub.f_is_subscribe = self.newsDetail.f_is_subscribe;
        sub.f_service_name = self.newsDetail.f_service_name;
        sub.f_service_count = self.newsDetail.f_service_count;
        controller.sub = sub;
        [self showViewController:controller sender:nil];
        return NO;
    } else {
        return YES;
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:kFontSize];
    if (fontSize <= 0) {
        fontSize = 100;
    }
    [self setFontSize:fontSize];
}

- (NSString *)touchBodyWithNews:(M_NewsDetail *)news_
{
    NSMutableString *body = [NSMutableString string];
    [body appendFormat:@"<div class=\"title\">%@</div>",news_.f_title];
    [body appendFormat:@"<div class=\"time\">%@</div>",news_.f_ptime];
    
    if (news_.f_body != nil) {
        [body appendString:news_.f_body = [news_.f_body stringByReplacingOccurrencesOfString:@"<img" withString:@"<img width =\"100%\""]];
        
    }
    
    return body;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationFade;
}

- (void)setFontSize:(CGFloat)fontSize {
    NSString *js = [NSString stringWithFormat:@"document.body.style.fontSize = \"%.0f",fontSize];
    js = [js stringByAppendingString:@"%\";"];
    [self.newsWebView stringByEvaluatingJavaScriptFromString:js];
}

- (void)switchFontSize:(UIPinchGestureRecognizer *)gesture
{
    if (gesture.state==UIGestureRecognizerStateEnded | gesture.state==UIGestureRecognizerStateCancelled) {
        
        NSString *js = @"";
        
        if (gesture.scale<1.0) {
            self.fontSizeScaleRate<=0.8?self.fontSizeScaleRate:(self.fontSizeScaleRate -= 0.1);
            
            js = [NSString stringWithFormat:@"document.body.style.fontSize = \"%.0f",self.fontSizeScaleRate*100];
            
        }
        else {
            self.fontSizeScaleRate>=1.2?self.fontSizeScaleRate:(self.fontSizeScaleRate += 0.1);
            
            js = [NSString stringWithFormat:@"document.body.style.fontSize = \"%.0f",self.fontSizeScaleRate*100];
            
        }
        js = [js stringByAppendingString:@"%\";"];
        [self.newsWebView stringByEvaluatingJavaScriptFromString:js];
    }
    
}
@end
